import 'dart:math';

import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class CustomPaintRoute extends StatefulWidget {
  const CustomPaintRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => CustomPaintRouteState();
}

class CustomPaintRouteState extends State<CustomPaintRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CustomPaint'),
      ),
      body: Center(
        child: RepaintBoundary(
          child: CustomPaint(
            size: const Size(350, 350),
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final logger = Logger(printer: LogfmtPrinter());

  @override
  void paint(Canvas canvas, Size size) {
    logger.i("paint...");
    var rect = Offset.zero & size;
    //画棋盘
    drawChessboard(canvas, rect);
    //画棋子
    drawPieces(canvas, rect);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;

  void drawChessboard(Canvas canvas, Rect rect) {
    // 绘制棋盘背景
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill
      ..color = const Color(0xFFDCC48C);
    canvas.drawRect(rect, paint);

    //画棋盘网格
    paint
      ..style = PaintingStyle.stroke // 实线
      ..color = Colors.black38
      ..strokeWidth = 1.0;

    var total = 15;

    for (int i = 0; i <= total; ++i) {
      double dy = rect.top + rect.height / total * i;
      canvas.drawLine(Offset(rect.left, dy), Offset(rect.right, dy), paint);
    }

    for (int i = 0; i <= total; ++i) {
      double dx = rect.left + rect.width / total * i;
      canvas.drawLine(Offset(dx, rect.top), Offset(dx, rect.bottom), paint);
    }
  }

  //画棋子
  void drawPieces(Canvas canvas, Rect rect) {
    double eWidth = rect.width / 15;
    double eHeight = rect.height / 15;

    // 黑子 画笔
    var paint = Paint()
      ..style = PaintingStyle.fill
      ..color = Colors.black;

    //画一个黑子
    canvas.drawCircle(
        Offset(rect.center.dx - eWidth / 2, rect.center.dy - eHeight / 2),
        min(eWidth / 2, eHeight / 2) - 2,
        paint);

    // 白子 画笔
    paint.color = Colors.white;
    canvas.drawCircle(
      Offset(rect.center.dx + eWidth / 2, rect.center.dy - eHeight / 2),
      min(eWidth / 2, eHeight / 2) - 2,
      paint,
    );
  }
}
